#include <stdio.h>  
#include <stdlib.h>  
#define FILE_NAME "text.txt"

/** 
 *读文件 
 */  

int ReadFile(const char* in_pc_file){      
    FILE *fpFile;  
    long int liLen;  
    char *szContent;  
    /* 以只读方式打开文件 */  
    if((fpFile = fopen (in_pc_file,"r")) == NULL){  
        printf("\nfile open error\n");  
        exit(0);  
    }  

    if (0 != fseek(fpFile,0,SEEK_END)) /* 定位到文件末尾 */  
    {
        abort();
    }

    liLen = ftell(fpFile); /* 得到文件大小 */  

    szContent = (char *)malloc((size_t)liLen + 1); /* 根据文件大小动态分配内存空间 */  

    if(NULL == szContent){  
        if (0 != fclose(fpFile)){
            abort();
        }
        return 0;  
    }  

    if (0 != fseek(fpFile, 0, SEEK_SET)){ /* 定位到文件开头 */  
        abort();
    }

    size_t uiSize = fread(szContent, (size_t)liLen, 1, fpFile);
    printf("Read %d bytes\n", uiSize);

    szContent[liLen]='0'; /* 字符串结束标志 */  

    printf("%s", szContent);  
    if (0 != fclose(fpFile))
    {
        abort();
    }
    free(szContent);  
    return 0;  
}  

/** 
 *写文件 
 */  

int WriteFile(const char* in_pc_file){  
    FILE *fpFile;  
    fpFile = fopen(in_pc_file, "w+");  
    if (NULL == fpFile)
    {
        return -1;
    }

    fprintf(fpFile, "hello world!\n");  

    printf("The file pointer is at byte \%ld\n", ftell(fpFile));  
    if (0 != fclose(fpFile))  
    {
        abort();
    }
    return 0;  
}  
  
int
main(void){  
#if 1
    if (0 != ReadFile(FILE_NAME))
    {
        printf("error!\n");
    }
#else
    if (0 != WriteFile(FILE_NAME))  
    {
        printf("error!\n");
    }
#endif
    return 0;  
}  
